/**
 * 加载状态管理工具
 * 统一管理页面加载状态和用户反馈
 */

class LoadingManager {
  constructor() {
    this.loadingStates = new Map()
    this.loadingQueue = new Set()
  }

  /**
   * 显示加载状态
   * @param {string} key - 加载状态的唯一标识
   * @param {Object} options - 加载选项
   */
  showLoading(key = 'default', options = {}) {
    const config = {
      title: '加载中...',
      mask: true,
      duration: 0,
      ...options
    }

    // 记录加载状态
    this.loadingStates.set(key, {
      startTime: Date.now(),
      config,
      active: true
    })

    this.loadingQueue.add(key)

    // 显示加载提示
    if (config.showUniLoading !== false) {
      uni.showLoading({
        title: config.title,
        mask: config.mask
      })
    }

    // 如果设置了超时时间，自动隐藏
    if (config.duration > 0) {
      setTimeout(() => {
        this.hideLoading(key)
      }, config.duration)
    }

    return key
  }

  /**
   * 隐藏加载状态
   * @param {string} key - 加载状态的唯一标识
   */
  hideLoading(key = 'default') {
    const loadingState = this.loadingStates.get(key)
    
    if (loadingState && loadingState.active) {
      loadingState.active = false
      loadingState.endTime = Date.now()
      loadingState.duration = loadingState.endTime - loadingState.startTime
      
      this.loadingQueue.delete(key)
      
      // 如果没有其他加载状态，隐藏uni的loading
      if (this.loadingQueue.size === 0) {
        uni.hideLoading()
      }
      
      console.log(`加载完成 [${key}]: ${loadingState.duration}ms`)
    }
  }

  /**
   * 隐藏所有加载状态
   */
  hideAllLoading() {
    this.loadingStates.forEach((state, key) => {
      if (state.active) {
        this.hideLoading(key)
      }
    })
    
    this.loadingQueue.clear()
    uni.hideLoading()
  }

  /**
   * 检查是否有活跃的加载状态
   * @param {string} key - 可选的特定加载状态
   * @returns {boolean}
   */
  isLoading(key) {
    if (key) {
      const state = this.loadingStates.get(key)
      return state && state.active
    }
    return this.loadingQueue.size > 0
  }

  /**
   * 获取加载状态信息
   * @param {string} key - 加载状态标识
   * @returns {Object|null}
   */
  getLoadingState(key) {
    return this.loadingStates.get(key) || null
  }

  /**
   * 显示进度加载
   * @param {string} key - 加载状态标识
   * @param {number} progress - 进度百分比 (0-100)
   * @param {string} message - 进度消息
   */
  showProgress(key, progress, message) {
    const state = this.loadingStates.get(key)
    if (state) {
      state.progress = progress
      state.progressMessage = message
      
      // 更新加载提示
      uni.showLoading({
        title: `${message} ${progress}%`,
        mask: true
      })
    }
  }

  /**
   * 显示带重试的加载状态
   * @param {string} key - 加载状态标识
   * @param {Function} retryFn - 重试函数
   * @param {Object} options - 选项
   */
  showLoadingWithRetry(key, retryFn, options = {}) {
    const config = {
      maxRetries: 3,
      retryDelay: 1000,
      title: '加载中...',
      ...options
    }

    let retryCount = 0

    const attemptLoad = () => {
      this.showLoading(key, { title: config.title })
      
      return retryFn()
        .then(result => {
          this.hideLoading(key)
          return result
        })
        .catch(error => {
          this.hideLoading(key)
          
          if (retryCount < config.maxRetries) {
            retryCount++
            
            return new Promise((resolve, reject) => {
              uni.showModal({
                title: '加载失败',
                content: `加载失败，是否重试？(${retryCount}/${config.maxRetries})`,
                confirmText: '重试',
                cancelText: '取消',
                success: (res) => {
                  if (res.confirm) {
                    setTimeout(() => {
                      attemptLoad().then(resolve).catch(reject)
                    }, config.retryDelay)
                  } else {
                    reject(error)
                  }
                }
              })
            })
          } else {
            throw error
          }
        })
    }

    return attemptLoad()
  }

  /**
   * 批量加载管理
   * @param {Array} loadTasks - 加载任务数组
   * @param {Object} options - 选项
   */
  async batchLoad(loadTasks, options = {}) {
    const config = {
      concurrent: false,
      showProgress: true,
      title: '加载中...',
      ...options
    }

    const batchKey = `batch_${Date.now()}`
    
    if (config.showProgress) {
      this.showLoading(batchKey, { title: config.title })
    }

    try {
      let results = []
      
      if (config.concurrent) {
        // 并发执行
        const promises = loadTasks.map((task, index) => {
          return task().catch(error => ({ error, index }))
        })
        
        results = await Promise.all(promises)
      } else {
        // 顺序执行
        for (let i = 0; i < loadTasks.length; i++) {
          if (config.showProgress) {
            const progress = Math.round((i / loadTasks.length) * 100)
            this.showProgress(batchKey, progress, `${config.title} (${i + 1}/${loadTasks.length})`)
          }
          
          try {
            const result = await loadTasks[i]()
            results.push(result)
          } catch (error) {
            results.push({ error, index: i })
          }
        }
      }
      
      return results
    } finally {
      this.hideLoading(batchKey)
    }
  }

  /**
   * 清理过期的加载状态记录
   * @param {number} maxAge - 最大保留时间（毫秒）
   */
  cleanup(maxAge = 5 * 60 * 1000) { // 默认5分钟
    const now = Date.now()
    
    this.loadingStates.forEach((state, key) => {
      if (!state.active && state.endTime && (now - state.endTime) > maxAge) {
        this.loadingStates.delete(key)
      }
    })
  }

  /**
   * 获取加载统计信息
   * @returns {Object}
   */
  getStats() {
    const stats = {
      active: this.loadingQueue.size,
      total: this.loadingStates.size,
      activeKeys: Array.from(this.loadingQueue),
      averageDuration: 0
    }

    const completedStates = Array.from(this.loadingStates.values())
      .filter(state => !state.active && state.duration)

    if (completedStates.length > 0) {
      const totalDuration = completedStates.reduce((sum, state) => sum + state.duration, 0)
      stats.averageDuration = Math.round(totalDuration / completedStates.length)
    }

    return stats
  }
}

// 创建全局实例
const loadingManager = new LoadingManager()

// 定期清理
setInterval(() => {
  loadingManager.cleanup()
}, 5 * 60 * 1000) // 每5分钟清理一次

// 导出便捷方法
export const showLoading = (key, options) => {
  return loadingManager.showLoading(key, options)
}

export const hideLoading = (key) => {
  return loadingManager.hideLoading(key)
}

export const hideAllLoading = () => {
  return loadingManager.hideAllLoading()
}

export const isLoading = (key) => {
  return loadingManager.isLoading(key)
}

export const showProgress = (key, progress, message) => {
  return loadingManager.showProgress(key, progress, message)
}

export const showLoadingWithRetry = (key, retryFn, options) => {
  return loadingManager.showLoadingWithRetry(key, retryFn, options)
}

export const batchLoad = (loadTasks, options) => {
  return loadingManager.batchLoad(loadTasks, options)
}

export default loadingManager